package com.example.good.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.good.entity.PermissionDO;
import com.example.good.entity.RolesPermissionDO;
import com.example.good.entity.User;
import com.example.good.entity.UserRolesDO;
import com.example.good.mapper.PermissionMapper;
import com.example.good.mapper.RolesPermissionMapper;
import com.example.good.mapper.UserMapper;
import com.example.good.mapper.UsersRolesMapper;
import com.example.good.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;
    
    @Autowired
    UsersRolesMapper usersRolesMapper;
    
    @Autowired
    RolesPermissionMapper rolesPermissionMapper;
    
    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public User getOneUserByName(String name) {
        return userMapper.getOneByName(name);
    }

    @Override
    public User login(String name) {
        User userLogin = userMapper.getOneByName(name);
        return userLogin;
    }

    @Override
    public List<String> getPermission(String name) {

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getName, name);
        User user = baseMapper.selectOne(wrapper);
        List<PermissionDO> permissions = getPermission(user.getId());
        List<String> permissionName = null;
        if (Objects.nonNull(permissions)){
            permissionName = permissions.stream().map(PermissionDO::getPermission).collect(Collectors.toList());
        }

        return permissionName;
    }

    /**
     * 获取权限列表
     * 
     * @return 返回权限列表
     */
    public List<PermissionDO> getPermission(Long userId){
        List<Long> roleIds = usersRolesMapper.getRolesIdByUserId(userId);
        
        LambdaQueryWrapper<RolesPermissionDO> wrapperRP = new LambdaQueryWrapper<>();
        wrapperRP.in(RolesPermissionDO::getPermissionId, roleIds);
        List<RolesPermissionDO> rolesPermissionDOS = rolesPermissionMapper.selectList(wrapperRP);
        List<Long> permissionIds = null;
        if (Objects.nonNull(rolesPermissionDOS)){
            permissionIds = rolesPermissionDOS.stream().map(RolesPermissionDO::getPermissionId).collect(Collectors.toList());
        }
        
        LambdaQueryWrapper<PermissionDO> wrapperPermission = new LambdaQueryWrapper<>();
        wrapperPermission.in(PermissionDO::getId, permissionIds);
        
        return permissionMapper.selectList(wrapperPermission);
    }
    
    
}
